/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gray.android.field;

import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import gray.Field;


/**
 *
 * @author martin
 */
public class RadioField <E extends Enum<E>> extends LinearLayout implements Field<Enum<E>,View> {
  
    private final Class<E> _enumData;
    private final RadioGroup _radio;
    private final RadioButton _butt[];
    private final Enum _choice[];
    
    private RadioField(Context context,final String title, Class<E> enumData){
        super(context);

        _enumData = enumData;
        _radio = new RadioGroup(context);
        _radio.setOrientation(RadioGroup.VERTICAL);
        
        Enum<E>[] all = enumData.getEnumConstants();
        _choice = new Enum[all.length];
        _butt = new RadioButton[all.length];
        
        int i = 0;
        for (Enum<E> enumVal: all) {
            _butt[i]  = new RadioButton(context);
            _butt[i].setText(enumVal.toString());
            _radio.addView(_butt[i]);
            _choice[i] = enumVal;
            i++;
        }
        
        _butt[0].setChecked(true);
        addView(_radio);
    }

    public static <E extends Enum<E>> Field<Enum<E>,View> factory(Context context,final String title, Class<E> enumData){
        return new RadioField(context,title, enumData);
    }
    
    @Override
    public Enum<E> input() {
    	for (int i=0;i<_butt.length;i++)
    		if (_butt[i].isChecked())
    			return _choice[i];
        return null;
    }
    
    @Override
    public View container() {
        return this;
    }
    
    @Override
    public Boolean ready() {
        return input()!=null;
    }
}
